const express = require('express')
const router = express.Router()
const Blog = require('../model/blog')

// 新增
router.post('/blog/add', async (req, res) => {
  const { title, author, sort, content, state, type } = req.body
  let nowTime = new Date()
  const data = await Blog.create({
    title,
    author,
    sort,
    content,
    state,
    type,
    createTime: nowTime,
  })
  if (data) {
    return res.send({
      code: 1,
      msg: '添加成功',
      data,
    })
  } else {
    return res.send({
      code: -1,
      msg: '添加失败',
      data,
    })
  }
})
// 修改
router.put('/blog/edit', async (req, res) => {
  const {
    _id,
    title,
    author,
    sort,
    content,
    state,
    type,
  } = req.body
  let nowTime = new Date()
  const data = await Blog.updateOne({_id}, {
    title,
    author,
    sort,
    content,
    state,
    type,
    updateTime: nowTime,
  })
  if(data.ok ===1){
    return res.send({
        code: 1,
        msg: '修改成功',
      })
  }else{
    return res.send({
        code: -1,
        msg: '修改失败',
      })
  }
  
})

// 查询列表带分页
router.get('/blog/getList', (req, res) => {
  const { page, limit, title = '' } = req.query
  Blog.find({}, function (err, data) {
    if (err)
      return res.send({
        code: -1,
        msg: '请求失败',
      })
    let count = data.length
    Blog.find({})
      .skip((page - 1) * parseInt(limit))
      .limit(parseInt(limit))
      .exec(function (err, data) {
        if (err)
          return res.send({
            code: -1,
            msg: '请求失败',
          })
        return res.send({
          code: 1,
          msg: '查询成功',
          total: count,
          data,
        })
      })
  })
})

// 根据id查询
router.get('/blog/getId', async (req, res) => {
  const { id } = req.query
  const data = await Blog.findById(id)
  if (data) {
    return res.send({
      code: 1,
      msg: '查询成功',
      data,
    })
  } else {
    return res.send({
      code: -1,
      msg: '查询失败',
      data,
    })
  }
})

// 根据id删除
router.delete('/blog/del', async (req, res) => {
  const { id } = req.query
  const data = await Blog.deleteOne({ _id: id })
  if (data.ok === 1) {
    return res.send({
      code: 1,
      msg: '删除成功',
    })
  } else {
    return res.send({
      code: -1,
      msg: '删除失败',
    })
  }
})

module.exports = router
